package com.zjt.smart.ui.base;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestManager;
import com.umeng.analytics.MobclickAgent;
import com.zjt.smart.manager.EventManager;
import com.zjt.smart.mvp.model.Event;
import com.zjt.smart.observer.EventObserver;

import butterknife.ButterKnife;

/**
 * @author zhengjianting
 * @time 2017/8/28 0028 上午 10:11
 */

public abstract class BaseFragment extends Fragment implements EventObserver {

    protected View mRootView;
    protected Context mContext;
    private boolean lastVisible = false;
    private RequestManager imgRequestManager;

    protected abstract int layoutId();

    //subclass can not override this method,and MUST override onActivityCreated()
    @Override
    public final void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        imgRequestManager = Glide.with(this);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mRootView = LayoutInflater.from(mContext).inflate(layoutId(), container, false);
        ButterKnife.bind(this, mRootView);
        EventManager.getInstance().regist(this);
        return mRootView;
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(getClass().getName());
        imgRequestManager.resumeRequests();
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(getActivity().getLocalClassName());
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.mContext = context;
    }

    @Override
    public void onDetach() {
        EventManager.getInstance().unregist(this);
        ButterKnife.unbind(this);
        super.onDetach();
        mContext = null;
        imgRequestManager.onTrimMemory(android.content.ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser && !lastVisible) {
            lastVisible = true;
            onShow();
        } else if (!isVisibleToUser && lastVisible) {
            lastVisible = false;
            onHide();
        }
    }

    public void onShow() {

    }

    public void onHide() {

    }

    public RequestManager getImgRequestManager(){
        return imgRequestManager;
    }

    @Override
    public void onEvent(Event event) {

    }

}
